<template>
  <CustomDialog :drag-dialog="dialogInfo" style="z-index:1201;">
    <el-form ref="form" :model="form" :rules="rules" :disabled="!form.busPageInfo.editable" size="mini" label-width="160px">
      <el-row :gutter="2">
        <el-col :span="12">
          <el-form-item label="产品编号" prop="busMainData.itemId">
            <BaseItemSelectDialog v-model="form.busMainData.itemCode" :editable="form.busPageInfo.editable && form.busMainData.funProcess === '10'" @itemSelectCallback="prodItemSelectCallback" />
          </el-form-item>
          <el-form-item label="MRP计算数" prop="busMainData.mrpQty">
            <el-input-number v-model.number="form.busMainData.mrpQty" :controls="false" :precision="0" :min="1" size="mini"/>
            <el-checkbox v-model="form.busMainData.autoAddNextLevel" true-label="Y" false-label="N">
              自动添加<IconHelp display-content="勾选后系统会自动搜寻物料对应的BOM,将BOM所有物料添加至该BOM明细下"/>
            </el-checkbox>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="生产部门" prop="busMainData.sysOrgCode">
            <OrgsetTreeSelect v-model="form.busMainData.sysOrgCode" :editable="form.busPageInfo.editable && form.busMainData.funProcess === '10'" :has-priv="false" style="width: 200px" />
          </el-form-item>
          <el-form-item label="模号" prop="busMainData.mouldNo">
            <el-input v-model="form.busMainData.mouldNo" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row :gutter="2">
      <el-col :span="24">
        <el-table
          :data="form.bomDetails"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          :default-expand-all="true"
          size="mini"
          highlight-current-row
          stripe
          border
          max-height="400px"
          row-key="id"
          style="width: 100%">
          <el-table-column v-if="form.busPageInfo.editable" label="操作" width="200">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="addSubBomItem(scope.$index, scope.row)">添加</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
          <el-table-column label="物料编号" width="280">
            <template slot-scope="scope">
              <BaseItemSelectDialog v-if="form.busPageInfo.editable" v-model="scope.row.itemCode" :param-data="scope.row" @itemSelectCallback="bomItemSelectCallback" />
              <span v-else>{{ scope.row.itemCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" prop="itemName" width="100" show-overflow-tooltip/>
          <el-table-column label="规格" prop="itemSpec" width="100" show-overflow-tooltip />
          <el-table-column label="库存单位" width="90">
            <template slot-scope="scope">
              <template v-for="item in dicts.item_unit">
                <span v-if="scope.row.stockUnit && scope.row.stockUnit === item.dictCode" :key="item.id" >{{ item.dictName }}</span>
              </template>
            </template>
          </el-table-column>
          <el-table-column label="使用量" width="100">
            <template slot="header" slot-scope="scope">
              使用量<IconHelp display-content="用量＝使用量+使用量*损耗率+使用量*固定损耗率+固定损耗数" />
            </template>
            <template slot-scope="scope">
              <el-input-number v-if="form.busPageInfo.editable" v-model.number="scope.row.reqQty" :controls="false" :precision="2" :min="0" size="mini" style="width: 90px"/>
              <span v-else>{{ scope.row.reqQty }}</span>
            </template>
          </el-table-column>
          <el-table-column label="损耗率" width="100">
            <template slot-scope="scope">
              <el-input-number v-if="form.busPageInfo.editable" v-model.number="scope.row.scrapRate" :controls="false" :precision="2" :min="0" size="mini" style="width: 90px"/>
              <span v-else>{{ scope.row.scrapRate }}</span>
            </template>
          </el-table-column>
          <el-table-column label="固定损耗率" width="100">
            <template slot-scope="scope">
              <el-input-number v-if="form.busPageInfo.editable" v-model.number="scope.row.fixScrapRate" :controls="false" :precision="2" :min="0" size="mini" style="width: 90px"/>
              <span v-else>{{ scope.row.fixScrapRate }}</span>
            </template>
          </el-table-column>
          <el-table-column label="固定损耗数" width="100">
            <template slot-scope="scope">
              <el-input-number v-if="form.busPageInfo.editable" v-model.number="scope.row.fixScrapQty" :controls="false" :precision="2" :min="0" size="mini" style="width: 90px"/>
              <span v-else>{{ scope.row.fixScrapQty }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料属性" width="120" prop="itemType">
            <template slot-scope="scope">
              <el-select :disabled="!form.busPageInfo.editable" v-model="scope.row.itemType" placeholder="物料属性">
                <el-option
                  v-for="(item) in dicts.item_type"
                  :key="item.id"
                  :label="item.dictName"
                  :value="item.dictCode"/>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="备注">
            <template slot-scope="scope">
              <el-input v-if="form.busPageInfo.editable" v-model="scope.row.rmk" />
              <span v-else>{{ scope.row.rmk }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col v-if="form.busPageInfo.editable" :span="24">
        <div class="el-table-add-row" style="width: 99.2%;" @click="addBomItem"><span>+ 添加</span></div>
      </el-col>
    </el-row>
    <div v-if="form.busPageInfo.editable" slot="footer" class="modal-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button v-permission="['SYS_ADMIN','COMMON_ADMIN','BASEBOM_ALL','BASEBOM_CHANGE','BASEBOM_CREATE']" :loading="loading" type="primary" @click="doSave">暂存</el-button>
      <el-button v-permission="['SYS_ADMIN','COMMON_ADMIN','BASEBOM_ALL','BASEBOM_SUBMIT']" :loading="loading" type="primary" @click="doSubmit">提交</el-button>
    </div>
  </CustomDialog>
</template>

<script>
import baseBom from '@/api/base/BaseBom'
import BaseItemSelectDialog from '@/views/components/BaseItemSelectDialog'
import OrgsetTreeSelect from '@/views/components/OrgsetTreeSelect'

export default {
  components: { BaseItemSelectDialog, OrgsetTreeSelect },
  dictTypes: ['item_type', 'item_unit'],
  props: {
    sup_this: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      isAdd: false,
      loading: false,
      style: 'width: 184px',
      dialogInfo: {
        name: 'baseBomMngFormDialog',
        title: 'BOM维护',
        fullScreen: true,
        width: 500,
        height: 90
      },
      form: {
        busMainData: {
          id: '',
          enableFlag: 'Y'
        },
        bomDetails: [],
        busPageInfo: {
        }
      },
      rules: {
        'busMainData.itemId': [
          { required: true, message: '请输入产品', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    cancel() {
      this.resetForm()
    },
    initDataOfBefore() {
    },
    displayDialog() {
      const { name } = this.dialogInfo
      this.$nextTick(() => {
        this.$modal.show(name)
      })
    },
    hiddenDialog() {
      const { name } = this.dialogInfo
      this.$nextTick(() => {
        this.$modal.hide(name)
      })
    },
    delTreeDetailRowById(bomDetails, id) {
      let index = 0
      bomDetails.forEach(tmpvo => {
        if (tmpvo.id === id) {
          bomDetails.splice(index, 1)
          return
        }
        if (tmpvo.children && tmpvo.children.length > 0) {
          this.delTreeDetailRowById(tmpvo.children, id)
        }
        index++
      })
    },
    handleDelete(index, row) {
      if (row.children && row.children.length > 0) {
        return
      }
      this.delTreeDetailRowById(this.form.bomDetails, row.id)
      this.form.bomDetails.splice(this.form.bomDetails.length)
    },
    addChildTreeDetailRowById(bomDetails, pid, detailRow) {
      bomDetails.forEach(tmpvo => {
        if (tmpvo.id === pid) {
          if (!tmpvo.children) {
            tmpvo.children = []
          }
          tmpvo.children.push(detailRow)
          return
        }
        if (tmpvo.children && tmpvo.children.length > 0) {
          this.addChildTreeDetailRowById(tmpvo.children, pid, detailRow)
        }
      })
    },
    addSubBomItem(index, row) {
      const addRow = { id: 'BOM' + new Date().getTime() + '-' + index, pid: row.id, 'itemCode': '', 'itemName': '', 'itemSpec': '', 'stockUnit': '', 'reqQty': 1, 'scrapRate': 0, 'fixScrapRate': 0, 'fixScrapQty': 0 }
      this.addChildTreeDetailRowById(this.form.bomDetails, row.id, addRow)
      this.form.bomDetails.splice(this.form.bomDetails.length)
    },
    addBomItem() {
      const length = this.form.bomDetails.length
      const addRow = { id: 'BOM' + new Date().getTime() + '-' + length, 'itemCode': '', 'itemName': '', 'itemSpec': '', 'stockUnit': '', 'reqQty': 1, 'scrapRate': 0, 'fixScrapRate': 0, 'fixScrapQty': 0 }
      this.form.bomDetails.push(addRow)
    },
    getBomDetailData(bomId, replaceIdFlag) {
      if (bomId) {
        baseBom.getBomDetailData(bomId, replaceIdFlag).then(res => {
          this.form.bomDetails = res.data
        })
      }
    },
    addData() {
      this.isAdd = true
      const data = { paramBean: {}}
      baseBom.toAdd(data).then(res => {
        this.displayDialog()
        this.form = res.data
        this.getBomDetailData(this.form.busMainData.id, false)
      }).catch(err => {
        console.log(err)
      })
    },
    copyData(mainId) {
      this.isAdd = true
      const data = { paramBean: { id: mainId }}
      baseBom.toCopy(data).then(res => {
        this.displayDialog()
        this.form = res.data
        this.getBomDetailData(this.form.busMainData.oldMainId, true)
      }).catch(err => {
        console.log(err)
      })
    },
    viewMainData(id) {
      this.isAdd = false
      const data = { paramBean: { id: id }}
      baseBom.viewMainData(data).then(res => {
        this.displayDialog()
        this.form = res.data
        this.getBomDetailData(this.form.busMainData.id, false)
      })
    },
    doSubmit() {
      this.doSingleSave(true)
    },
    doSave() {
      this.doSingleSave(false)
    },
    doSingleSave(isSubmit) {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.form.formSubmit = isSubmit
          this.loading = true
          if (this.isAdd) {
            this.doAdd()
          } else {
            this.doEdit()
          }
        }
      })
    },
    doAdd() {
      baseBom.addOrEdit(this.form).then(res => {
        this.resetForm()
        this.loading = false
        this.sup_this.init()
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    doEdit() {
      baseBom.addOrEdit(this.form).then(res => {
        this.resetForm()
        this.loading = false
        this.sup_this.init()
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    resetForm() {
      this.hiddenDialog()
      this.$refs['form'].resetFields()
    },
    changeData(busId) {
      const data = { paramBean: { id: busId }}
      baseBom.toChange(data).then(res => {
        this.displayDialog()
        this.form = res.data
        this.getBomDetailData(this.form.busMainData.oldMainId, true)
      }).catch(err => {
        this.dialog = false
        console.log(err)
      })
    },
    prodItemSelectCallback(selectedRow, selectObj) {
      this.form.busMainData.itemId = ''
      this.form.busMainData.itemCode = ''
      if (selectedRow) {
        this.form.busMainData.itemId = selectedRow.id
        this.form.busMainData.itemCode = selectedRow.itemCode
      }
    },
    bomItemSelectCallback(selectedRow, selectObj, paramData) {
      paramData.itemId = ''
      paramData.itemCode = ''
      paramData.itemName = ''
      paramData.itemSpec = ''
      paramData.stockUnit = ''
      paramData.itemType = ''
      if (selectedRow) {
        paramData.itemId = selectedRow.id
        paramData.itemName = selectedRow.itemName
        paramData.itemCode = selectedRow.itemCode
        paramData.itemSpec = selectedRow.itemSpec
        paramData.stockUnit = selectedRow.stockUnit
        paramData.itemType = selectedRow.itemType
      }
      this.setTreeDetailRowById(this.form.bomDetails, paramData)
      this.form.bomDetails.splice(this.form.bomDetails.length)
    },
    setTreeDetailRowById(bomDetails, detailRow) {
      bomDetails.forEach(tmpvo => {
        if (tmpvo.id === detailRow.id) {
          tmpvo = detailRow
          return
        }
        if (tmpvo.children && tmpvo.children.length > 0) {
          this.setTreeDetailRowById(tmpvo.children, detailRow)
        }
      })
    }
  }
}
</script>
